package com.example.block_chain.service.impl.admin;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.block_chain.RabbitMQ.Producer;
import com.example.block_chain.common.AppHttpCodeEnum;
import com.example.block_chain.common.ResponseResult;
import com.example.block_chain.domain.pbft.VoteEnum;
import com.example.block_chain.domain.pbft.VoteInfo;
import com.example.block_chain.domain.pojo.Admin;
import com.example.block_chain.domain.pojo.Award;
import com.example.block_chain.domain.vo.AwardVo;
import com.example.block_chain.mapper.AdminMapper;
import com.example.block_chain.mapper.AwardMapper;
import com.example.block_chain.service.OSSUploadService;
import com.example.block_chain.service.admin.AwardAuditingService;
import com.example.block_chain.service.blockChain.BlockService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.block_chain.common.SystemParameters;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.util.*;

import static com.example.block_chain.service.impl.award.AwardServiceImpl.getAwardPictureUrl;

@Service
public class AwardAuditingServiceImpl implements AwardAuditingService {
    @Autowired
    private AwardMapper awardMapper;

    @Autowired
    private AdminMapper adminMapper;

    @Resource
    OSSUploadService ossUploadService;

    @Resource
    BlockService blockService;

    @Resource
    Producer producer;

    @Override
    public ResponseResult passAward(String awardId, Integer authority, String aNo) {
        Award award = awardMapper.selectById(awardId);
        if (authority - 1 != award.getStatus())
            return ResponseResult.errorResult(AppHttpCodeEnum.AUTHORITY_DEFICIENCY);
        String aNoTmp = award.getANo();
        if (aNoTmp == null || aNoTmp.isBlank()) {
            award.setANo(aNo);
        } else {
            //拼接管理员的工号
            award.setANo(aNoTmp + "," + aNo);
        }

        award.setStatus(authority);
        awardMapper.updateById(award);

        if (authority.equals(3)) {
            //奖项通过校级审核，上区块链
            if (!blockService.haveCode(award.getSchoolCode() + ":" + award.getSNo())) {
                return ResponseResult.errorResult(AppHttpCodeEnum.STUDENT_NOT_FOUND);
            }
            if (blockService.haveAward(award.getDigest())) {
                return ResponseResult.errorResult(AppHttpCodeEnum.AWARD_EXISTS);
            }
            VoteInfo voteInfo = blockService.createAwardBlock(award);
            voteInfo.setCode(VoteEnum.REQUEST.getCode());
            System.out.println(voteInfo);
            producer.sendMessage(voteInfo);
            return ResponseResult.okResult();
        }

        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult refuseAward(String awardId, Integer authority, String aNo) {
        Award award = awardMapper.selectById(awardId);
        if (authority - 1 != award.getStatus())
            return ResponseResult.errorResult(AppHttpCodeEnum.AUTHORITY_DEFICIENCY);
        String aNoTmp = award.getANo();
        if (aNoTmp == null || aNoTmp.isBlank()) {
            award.setANo(aNo);
        } else {
            //拼接管理员的工号
            award.setANo(aNoTmp + "," + aNo);
        }

        award.setStatus(-authority);
        awardMapper.updateById(award);

        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult counsellorSelectAuditAward(String classCode, String facultyCode, String schoolCode, String status, Integer page, Integer pageSize) throws UnsupportedEncodingException {
        //默认为0
        if (status == null || status.isEmpty()) {
            status = "0";
        }

        QueryWrapper<Award> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("class_code", classCode).eq("faculty_code", facultyCode)
                .eq("school_code", schoolCode).eq("status", status);

        List<Award> auditingAwards = getAwardPage(page, pageSize, queryWrapper);

        List<AwardVo> awardVoList = toAwardVo(auditingAwards);

        return ResponseResult.okResult(awardVoList);
    }

    @Override
    public ResponseResult facultySelectAuditAward(String facultyCode, String schoolCode, String status, Integer page, Integer pageSize) throws UnsupportedEncodingException {
        //默认为1
        if (status == null || status.isEmpty()) {
            status = "1";
        }
        //查找需要的待审核
        QueryWrapper<Award> queryWrapperFaculty = new QueryWrapper<>();
        queryWrapperFaculty.eq("school_code", schoolCode).eq("faculty_code", facultyCode)
                .eq("status", status);
        List<Award> auditingAwards = getAwardPage(page, pageSize, queryWrapperFaculty);

        List<AwardVo> awardVoList = toAwardVo(auditingAwards);

        return ResponseResult.okResult(awardVoList);
    }

    @Override
    public ResponseResult schoolSelectAuditAward(String schoolCode, String status, Integer page, Integer pageSize) throws UnsupportedEncodingException {
        //默认为2
        if (status == null || status.isEmpty()) {
            status = "2";
        }
        QueryWrapper<Award> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("school_code", schoolCode).eq("status", status);

        List<Award> auditingAwards = getAwardPage(page, pageSize, queryWrapper);
        List<AwardVo> awardVoList = toAwardVo(auditingAwards);

        return ResponseResult.okResult(awardVoList);
    }


    @Override
    public List<AwardVo> toAwardVo(List<Award> auditingAwards) {
        List<AwardVo> awardVoList = new LinkedList<>();
        for (Award award : auditingAwards) {
            AwardVo awardVo = new AwardVo();
            BeanUtils.copyProperties(award, awardVo);

            //添加审核信息
            awardVo.setStatusInfo(getAwardStatus(award.getStatus()));

            Map<String, Admin> adminMap = new HashMap<>();
            String aNo = award.getANo();
            if (aNo == null) {
                awardVoList.add(awardVo);
                continue;
            }

            String[] aNoArray = aNo.split(",");
            System.out.println("aafdsss2=" + aNoArray.length);

            Admin counsellor = new Admin();
            Admin faculty = new Admin();
            Admin school = new Admin();
            String counsellorAno = "";
            String facultyAno = "";
            String schoolAno = "";
            if (aNoArray.length >= 1) {
                counsellorAno = aNoArray[0];

                QueryWrapper<Admin> queryWrapper1 = new QueryWrapper<>();
                queryWrapper1.eq("a_no", counsellorAno);
                counsellor = adminMapper.selectOne(queryWrapper1);
                adminMap.put("counsellor", counsellor);
            }
            if (aNoArray.length >= 2) {
                facultyAno = aNoArray[1];

                QueryWrapper<Admin> queryWrapper2 = new QueryWrapper<>();
                queryWrapper2.eq("a_no", facultyAno);
                faculty = adminMapper.selectOne(queryWrapper2);
                adminMap.put("faculty", faculty);
            }
            if (aNoArray.length >= 3) {
                schoolAno = aNoArray[2];

                QueryWrapper<Admin> queryWrapper3 = new QueryWrapper<>();
                queryWrapper3.eq("a_no", schoolAno);
                school = adminMapper.selectOne(queryWrapper3);
                adminMap.put("school", school);
            }
            awardVo.setAdminMap(adminMap);

            awardVoList.add(awardVo);
        }

        return awardVoList;
    }

    //审核奖状接口
    @Override
    public ResponseResult selectAuditAward(String classCode, String facultyCode, String schoolCode, Integer status, Integer page, Integer pageSize, HttpSession session) throws UnsupportedEncodingException {
        LambdaQueryWrapper<Award> queryWrapper = new LambdaQueryWrapper<>();
        Admin admin = (Admin) session.getAttribute("admin");
        if (Objects.equals(admin.getAuthority(), SystemParameters.AUTHORITY_1) && classCode.isBlank()) {
            List<String> classCodes = (List<String>) session.getAttribute("admin" + admin.getId());
            queryWrapper.in(Award::getClassCode, classCodes);
        }
        queryWrapper.eq(!classCode.isBlank(), Award::getClassCode, classCode).eq(facultyCode == null, Award::getFacultyCode, facultyCode)
                .eq(Award::getSchoolCode, schoolCode).eq(Award::getStatus, status);
        queryWrapper.orderByAsc(Award::getCreateTime);
        Page<Award> awardPage = awardMapper.selectPage(new Page<>(page, pageSize), queryWrapper);

        List<String> list = new ArrayList<>();
        List<Award> awards = awardPage.getRecords();
        getAwardPictureUrl(list, awards, ossUploadService);
        List<AwardVo> awardVos = toAwardVo(awards);
        Page<AwardVo> awardVoPage = new Page<>();
        awardPage.setRecords(awards);
        BeanUtils.copyProperties(awardPage, awardVoPage);
        awardVoPage.setRecords(awardVos);
        return ResponseResult.okResult(awardVoPage);
    }

    private List<Award> getAwardPage(Integer page, Integer pageSize, QueryWrapper<Award> queryWrapper) throws UnsupportedEncodingException {
        IPage<Award> awardIPage = new Page<>(page, pageSize);

        List<Award> records = awardMapper.selectPage(awardIPage, queryWrapper).getRecords();
        List<String> list = new ArrayList<>();
        getAwardPictureUrl(list, records, ossUploadService);
        return records;
    }

    private String getAwardStatus(Integer status) {
        String info = "";
        if (Objects.equals(status, SystemParameters.WAIT_COUNSELLOR_PASS)) {
            info = SystemParameters.WAIT_COUNSELLOR_PASS_INFO;
        } else if (Objects.equals(status, SystemParameters.COUNSELLOR_PASS)) {
            info = SystemParameters.COUNSELLOR_PASS_INFO;
        } else if (Objects.equals(status, SystemParameters.COUNSELLOR_NO_PASS)) {
            info = SystemParameters.COUNSELLOR_NO_PASS_INFO;
        } else if (Objects.equals(status, SystemParameters.FACULTY_PASS)) {
            info = SystemParameters.FACULTY_PASS_INFO;
        } else if (Objects.equals(status, SystemParameters.FACULTY_NO_PASS)) {
            info = SystemParameters.FACULTY_NO_PASS_INFO;
        } else if (Objects.equals(status, SystemParameters.SCHOOL_PASS)) {
            info = SystemParameters.SCHOOL_PASS_INFO;
        } else if (Objects.equals(status, SystemParameters.SCHOOL_NO_PASS)) {
            info = SystemParameters.SCHOOL_NO_PASS_INFO;
        }
        return info;
    }
}
